import { createRouter, createWebHashHistory } from 'vue-router'

import Home from '@/views/Home.vue';
import Login from '@/views/Login.vue';
import Publish from '@/views/Publish.vue';
import My from '@/views/My.vue';
import Error from '@/views/Error.vue';
import request from "@/utils/request";

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home,
    },
    {
        path: '/login',
        name: 'Login',
        component: Login,
    },
    {
        path: '/publish',
        name: 'Publish',
        component: Publish,
    },
    {
        path: '/my',
        name: 'My',
        component: My,
    },
    {
        path: '/:pathMatch(.*)',
        name: 'Error',
        component: Error,
    },
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

router.beforeEach(async (to, from, next) => {
    if (to.name === "Login" || to.name === "Home") {
        next();
    } else {
        const res = await request.post('/api/user/check')
        if (res.data) {
            next();
        } else {
            localStorage.removeItem('token')
            next("/login");
        }
    }
})

export default router